import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import router from '@/router'
// import { getTimeStamp } from '@/utils/auth'
// const TimeOut = 5000
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    const { token } = store.getters
    if (token) {
      config.headers['x-token'] = token
    }
    // 有token情况下，发送请求之前，主动校验请求时间
    // if (isCheckTimeOut) {
    //   store.dispatch('user/logout')
    //   router.push('/login')
    //   return Promise.reject('TOKEN过期')
    // }
    // do something before request is sent
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const { errno, errmsg, data } = response.data
    if (errno === 0) {
      return data
    } else if (errno === 9997) {
      store.dispatch('user/logout')
      router.push('/login')
    } else {
      Message.error(errmsg)
      return Promise.reject(errmsg)
    }
  },
  error => {
    console.log('err' + error) // for debug
    return Promise.reject(error)
  }
)
// function isCheckTimeOut() {
//   const tokenTime = getTimeStamp()
//   const time = (Date.now() - tokenTime) / 1000 > TimeOut
//   return time
// }

export default service
